package com.ruanyun.modular.ry.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 腾讯云存储
 */
@Slf4j
@Component
public class COSUtil {

    public static String accessKeyId = "AKID5g2C8oUBXbJmyt7VCepk03yHOGxOoQ1N";
    public static String accessKeySecret = "GTP5VgsnRo68xXrDI6gDTebGekhaXFph";
    public static String bucketName = "book-1256506211";
    public static String host = "https://book-1256506211.cos.ap-nanjing.myqcloud.com/";
    public static String REGION = "ap-nanjing";

    /**
     * 创建cosClient 客户端
     *
     * @return
     */
    public static COSClient getCOSClient() {
        COSCredentials cred = new BasicCOSCredentials(accessKeyId, accessKeySecret);
        Region region = new Region(REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    public static String upload(MultipartFile multipartFile) {
        CommonUtil commonUtil = new CommonUtil();
        File file = commonUtil.getFileByMultipartFile(multipartFile);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        if (null == file) {
            return null;
        }
        COSClient cosClient = getCOSClient();
        String fileUrl = null;
        try {
            //容器不存在，就创建
            if (!cosClient.doesBucketExist(bucketName)) {
                cosClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                // 设置 bucketName 的权限为 Private(私有读写), 其他可选有公有读私有写, 公有读写
                createBucketRequest.setCannedAcl(CannedAccessControlList.PublicReadWrite);
                cosClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            fileUrl = System.currentTimeMillis() + UUID.randomUUID().toString().replace("-", "").toUpperCase() + suffix;
            //上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl, file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //设置权限 这里是公开读
            cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (null != putObjectResult) {
                System.out.println("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                File del = new File(file.toURI());
                del.delete();
                return fileUrl;
            }
        } catch (CosServiceException oe) {
            System.out.println(oe.getMessage());
        } catch (CosClientException ce) {
            System.out.println(ce.getMessage());
        } finally {
            //关闭
            cosClient.shutdown();
        }
        return fileUrl;
    }
}
